package com.zzyk.web.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.zzyk.main.configuration.aspectj.annotation.OperaLog;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.controller.BaseController;
import com.zzyk.main.model.pojo.Organization;
import com.zzyk.main.model.pojo.RdOrganizationArea;
import com.zzyk.main.model.pojo.RdUserArea;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.model.vo.Message;
import com.zzyk.main.model.vo.OrganizationInfo;
import com.zzyk.main.service.ISysOrganizationService;
import com.zzyk.main.service.ISysUserService;
import com.zzyk.main.service.RdOrganizationAreaService;
import com.zzyk.main.service.RdUserAreaService;
import com.zzyk.main.utils.FTPUtils;
import com.zzyk.main.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping({"/sys/org"})
public class SysOrganizationController extends BaseController {

    @Resource
    private ISysOrganizationService organizationService;
    @Resource
    private ISysUserService userService;
    @Resource
    private RdOrganizationAreaService organizationAreaService;
    @Resource
    private RdUserAreaService userAreaService;
    @Resource
    private FTPUtils ftp;

    @Value("${ftp.logoDir}")
    private String logoDir;
    @Value("${ftp.photoDir}")
    private String photoDir;

    @RequestMapping("/getAreaById")
    public List<OrganizationInfo> getAreaById(Integer id) {
        return organizationService.getAreaById(id);
    }

    @RequestMapping("list")
    public Message list(Organization organization) throws UserException {
        SysUser sysUser = currentUser();
        organization.setArea(sysUser.getArea());
        setPage();
        List<OrganizationInfo> list = organizationService.list(organization);
        PageInfo<OrganizationInfo> info = new PageInfo<>(list);
        return Message.success("组织机构查询成功")
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }

    @RequestMapping("get")
    public Message get(@RequestParam("ids") String[] ids) {
        return Message.success().addData("data", organizationService.getList(ids));
    }

    @RequestMapping("info")
    public Message info(@RequestParam("id") Integer id) {
        return Message.success().addData("data", organizationService.get(id));
    }

    @OperaLog("修改组织机构信息")
    @RequestMapping("save")
    @Transactional
    public Message save(OrganizationInfo organization) throws UserException {
        if (ObjectUtil.isNotNull(organization.getCounty()) && organization.getCounty().equals("请选择")) {
            organization.setCounty(null);
        }
        if (organization == null) {
            throw new UserException("缺少参数");
        }
        if (organization.getLogoFile() != null && !"".equals(organization.getLogoFile().getOriginalFilename())) {
            try {
                MultipartFile file = organization.getLogoFile();
                String filename = IdUtil.fastSimpleUUID() + "." + FileUtils.getExt(file.getOriginalFilename());
                organization.setLogo(logoDir + "/" + filename);
                ftp.upload(file.getInputStream(), filename, logoDir);
                ftp.upload(organization.getMinLogo().getInputStream(), "min" + filename, logoDir);
            } catch (IOException e) {
                e.printStackTrace();
                throw new UserException("logo上传失败");
            }
        }
        if (StringUtils.isNotBlank(organization.getAddress())) {
            String addresse = organization.getAddress().replace(organization.getCity(), "");
            addresse = addresse.replace(organization.getProvince(), "");
            organization.setAddress(addresse);
        }
        if (organization.getPhotoFile() != null && !"".equals(organization.getPhotoFile().getOriginalFilename())) {
            try {
                MultipartFile file = organization.getPhotoFile();
                String filename = IdUtil.fastSimpleUUID() + "." + FileUtils.getExt(file.getOriginalFilename());
                organization.setPhoto(photoDir + "/" + filename);
                ftp.upload(file.getInputStream(), filename, photoDir);
                ftp.upload(organization.getMinPhoto().getInputStream(), "min" + filename, photoDir);
            } catch (IOException e) {
                e.printStackTrace();
                throw new UserException("photo上传失败");
            }
        }
        if (organization.getId() != null) {
            return Message.success().addData("data", organizationService.update(organization));
        } else {
            if (organizationService.get(organization.getName()) != null) {
                throw new UserException("已存在同名组织机构");
            }
            if (organizationService.add(organization) > 0 && organization.getId() != null) {
                RdOrganizationArea organizationArea = new RdOrganizationArea();
                organizationArea.setParentId(organization.getId());
                organizationArea.setChild(organization.getId());
                organizationAreaService.save(organizationArea);
                SysUser sysUser = new SysUser();
                sysUser.setUsername(organization.getPhone());
                sysUser.setEnterprise(organization.getId());
                sysUser.setDisplayName(organization.getContact());
                sysUser.setPassword("123456");
                sysUser.setDesc(organization.getName());
                sysUser.setStatus(1);
                RdUserArea userArea = new RdUserArea();
                userService.newUser(sysUser);
                userArea.setUser(sysUser.getId());
                userArea.setOrganization(organizationArea.getId());
                userAreaService.save(userArea);
                return Message.success().addData("data", organizationService.update(organization));
            } else {
                throw new UserException("添加组织机构失败");
            }
        }
    }

    @RequestMapping("del")
    public Message del(@RequestParam("id") Integer id) {
        return Message.success().addData("data", organizationService.del(id));
    }
}
